<?php

namespace App\Observers;

use App\Helpers\KeyHandler;
use App\Models\Customer;
use App\Models\SalePerformance;
use Illuminate\Support\Facades\Cache;

class SalePerformanceObserver
{


    public function deleted(SalePerformance $performance)
    {
        //删除后，如果没有业绩数据了，需要销售接待数据的成交状态
        if (SalePerformance::query()->where('customer_id', $performance->customer_id)->doesntExist()) {
            Customer::query()->where('id', $performance->customer_id)->update([
                'deal' => null
            ]);
        }

        //删除统计缓存
        Cache::forget(sprintf(KeyHandler::SALE_STATISTICS, 'day', $performance->created_at->year . '-' . $performance->created_at->month));
        Cache::forget(sprintf(KeyHandler::SALE_STATISTICS, 'month', $performance->created_at->year . '-' . $performance->created_at->month));
    }

    public function saved(SalePerformance $performance)
    {
        //删除统计缓存
        Cache::forget(sprintf(KeyHandler::SALE_STATISTICS, 'day', $performance->created_at->year . '-' . $performance->created_at->month));
        Cache::forget(sprintf(KeyHandler::SALE_STATISTICS, 'month', $performance->created_at->year . '-' . $performance->created_at->month));
    }


}
